<template>
  <div class="feedback-container">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <span>训练反馈</span>
        </div>
      </template>

      <el-table :data="feedbackList" style="width: 100%" v-loading="loading" border>
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="日期" width="120">
          <template #default="scope">
            <div class="date-cell">
              {{ formatDate(scope.row.date) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="coach" label="教练" width="120" />
        <el-table-column prop="program" label="训练项目" min-width="150" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              :max="5"
              :allow-half="false"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="反馈内容" min-width="200">
          <template #default="scope">
            <div class="content-cell">
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              size="small"
              @click="viewFeedbackDetail(scope.row)"
              :disabled="!scope.row.response"
            >
              查看回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        layout="total, prev, pager, next, jumper"
        :total="totalFeedbacks"
        @current-change="handleCurrentChange"
      />

      <!-- 反馈详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="反馈详情" width="60%">
        <div v-if="selectedFeedback" class="feedback-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="提交日期">
              {{ formatDateTime(selectedFeedback.date) }}
            </el-descriptions-item>
            <el-descriptions-item label="教练">
              {{ selectedFeedback.coach }}
            </el-descriptions-item>
            <el-descriptions-item label="训练项目">
              {{ selectedFeedback.program }}
            </el-descriptions-item>
            <el-descriptions-item label="评分">
              <el-rate
                v-model="selectedFeedback.rating"
                disabled
                :max="5"
                :allow-half="false"
                :texts="['很差', '较差', '一般', '良好', '优秀']"
                show-text
              />
            </el-descriptions-item>
            <el-descriptions-item label="反馈内容">
              {{ selectedFeedback.content || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(selectedFeedback.status)">
                {{ getStatusText(selectedFeedback.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="回复内容" v-if="selectedFeedback.response">
              {{ selectedFeedback.response }}
            </el-descriptions-item>
            <el-descriptions-item label="回复时间" v-if="selectedFeedback.replyTime">
              {{ formatDateTime(selectedFeedback.replyTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import requestUtil from '@/util/request.js'

// 数据和状态
const feedbackList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalFeedbacks = ref(0)

// 对话框控制
const detailDialogVisible = ref(false)
const selectedFeedback = ref(null)

// 获取训练反馈数据
const fetchFeedbackList = async () => {
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    ElMessage.error('未找到用户信息')
    return
  }

  loading.value = true
  try {
    const response = await requestUtil.get(`/student_training/trainings/user/${userId}`)

    if (response.data && response.data.data) {
      // 处理数据，只显示有反馈内容的训练记录
      const rawData = response.data.data.filter(item => item.feedback || item.response)

      feedbackList.value = rawData.map(item => ({
        id: item.training_id,
        date: item.create_at,
        coach: item.coach_name,
        program: item.program_name,
        content: item.feedback || item.content || '无反馈内容',
        rating: item.rating || 0,
        status: item.response ? 'completed' : 'pending',
        response: item.response || '',
        replyTime: item.response ? new Date().toISOString() : null // 这里需要根据实际数据调整
      }))

      totalFeedbacks.value = feedbackList.value.length
    } else {
      feedbackList.value = []
      ElMessage.info('暂无反馈记录')
    }
  } catch (error) {
    ElMessage.error('获取反馈列表失败: ' + (error.message || '未知错误'))
    console.error('获取反馈列表失败:', error)
    feedbackList.value = []
  } finally {
    loading.value = false
  }
}

// 查看反馈详情
const viewFeedbackDetail = (feedback) => {
  selectedFeedback.value = feedback
  detailDialogVisible.value = true
}

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 状态类型映射
const getStatusType = (status) => {
  switch (status) {
    case 'completed': return 'success'
    case 'pending': return 'warning'
    default: return ''
  }
}

// 状态文本映射
const getStatusText = (status) => {
  switch (status) {
    case 'completed': return '已回复'
    case 'pending': return '待回复'
    default: return status
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 组件挂载时获取数据
onMounted(() => {
  fetchFeedbackList()
})
</script>

<style lang="scss" scoped>
.feedback-container {
  padding: 20px 0;

  .feedback-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
    }
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }

  .date-cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .content-cell {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .feedback-detail {
    padding: 10px;
  }

  .dialog-footer {
    text-align: right;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: stretch;
    }
  }
}
</style>
